package com.hua.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hua.common.Response;
import com.hua.common.ResponseCode;
import com.hua.domain.*;
import com.hua.domain.domainVo.CategoryVo;
import com.hua.domain.domainVo.CommodityPriceVo;
import com.hua.exception.BusinessException;
import com.hua.mapper.*;
import com.hua.service.CategoryService;
import com.hua.service.CommodityInfoService;
import com.hua.util.RedisCache;
import com.hua.util.ResultUtils;
import com.mysql.cj.x.protobuf.Mysqlx;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.hua.common.ResponseCode.SUCCESS;

/**
* @author cl
* @description 针对表【category(商品种类表)】的数据库操作Service实现
* @createDate 2022-10-19 11:10:27
*/
@Service
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
    implements CategoryService{

    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisCache redisCache;

    @Resource
    private CommodityInfoMapper commodityInfoMapper;

    @Resource
    private FlavorMapper flavorMapper;

    @Resource
    private CommodityInfoService commodityInfoService;


    @Resource
    private ScaleMapper scaleMapper;


    @Resource
    private PriceMapper priceMapper;

    /**
     * feng  redis-->hua
     * @return
     */
    @Override
    public Response<List<Category>> getCategory() {

        List<Category> categories = redisCache.getCacheObject("categories");

        if(categories!=null){
            return new Response<List<Category>>(200,categories,"商品种类全部列表");
        }
        categories = categoryMapper.selectList(null);

        if(categories==null){
            throw new BusinessException(ResponseCode.SYSTEM_ERROR,"数据为空,请添加数据");
        }
        redisCache.setCacheObject("categories",categories,30, TimeUnit.MINUTES);

        return new Response<List<Category>>(200,categories,"商品种类全部列表");
    }

    /**
     * hua
     * @param
     * @return
     */
    @Override
    public Response<String> addCategory(CategoryVo categoryVo) {
        Long count = categoryMapper.selectCount(null);
        if(count==null){
            count=1L;
        }else {
            count++;
        }
        categoryVo.getCategory().setCategoryId(Integer.parseInt(count.toString()));
        User user = userMapper.selectById(categoryVo.getUserId());
        categoryVo.getCategory().setCreateUser(user.getUsername());
        categoryVo.getCategory().setUpdateUser(user.getUsername());
        categoryVo.getCategory().setUpdateTime(new Date());
        categoryVo.getCategory().setCreateTime(new Date());

        if (categoryMapper.insert(categoryVo.getCategory())>0){
            redisCache.deleteObject("categories");
            return ResultUtils.success(ResponseCode.SUCCESS,"添加成功");
        }

        throw new BusinessException(ResponseCode.INPUT_ERROR,"添加失败");
    }

    /**
     * feng
     * @param categoryId
     * @return
     */
    @Override
    @Transactional
    public Response<String> deleteCategoryById(Integer categoryId) {
        Category queryResult = categoryMapper.selectOne(new QueryWrapper<Category>().eq("categoryId", categoryId));
        commodityInfoService.delete(queryResult.getCategoryName());
        if(categoryMapper.deleteById(categoryId)>0){
            redisCache.deleteObject("categories");
            redisCache.deleteObject("CommodityPriceVo"+queryResult.getCategoryName());
            return ResultUtils.success(ResponseCode.SUCCESS,"删除成功");
        }
        throw new BusinessException(ResponseCode.PARAMS_ERROR,"删除失败");
    }

    @Override
    public int updateCurrentOfUserFace(String url, String newName, CategoryVo categoryVo) {
        Category category = categoryVo.getCategory();
        User user = userMapper.selectById(categoryVo.getUserId());

        category.setUpdateUser(user.getUsername());
        category.setCreateUser(user.getUsername());
        category.setSort(99);
        if(categoryMapper.insert(category)>0){
            return 1;
        }else {
            return 0;
        }
    }

    /**
    * @Description: 根据商品种类名称获取商品加上不同规格的价格
    * @Param: String 商品种类名称
    * @return:  Response<List<CommodityPriceVo>>
    * @Author: 黄燕峰
    */
    @Override
    public Response<List<CommodityPriceVo>> getKind(String kind) {
//      从缓存中获取
        List<CommodityPriceVo> listResult = redisCache.getCacheList("CommodityPriceVo"+kind);
        if(listResult.size()!=0){
            return ResultUtils.success(SUCCESS,listResult,"","返回特定商品类型的所有商品加价格");
        }
//        创建根据商品种类查询所有商品的条件
        LambdaQueryWrapper<CommodityInfo> queryWrapper = new LambdaQueryWrapper<CommodityInfo>();
        queryWrapper.eq(CommodityInfo::getCommodityType,kind);
//      根据查询条件从数据库中查询数据
        List<CommodityInfo> commodityInfos = commodityInfoMapper.selectList(queryWrapper);
//      如果数据为空则抛出异常
        if(commodityInfos.size()==0){
           return ResultUtils.success(SUCCESS,null,null);
        }
//        遍历所有数据
        commodityInfos.forEach(c->{
             Flavor flavor = flavorMapper.selectOne(new LambdaQueryWrapper<Flavor>().eq(Flavor::getFlavorId,c.getFlavorId()));

             //            从flavor中取出scaleId封装到数组中
            List<BigDecimal> price =null;
                if (flavor!=null) {
                    String[] scaleIdsSpring = flavor.getScaleId().split(",");
                    Integer[] scaleIds = new Integer[scaleIdsSpring.length];
                    for (int i = 0; i < scaleIdsSpring.length; i++) {
                        scaleIds[i] = Integer.parseInt(scaleIdsSpring[i]);
                    }

//            根据数组中的每一个scaleId获取Scale集合
                    List<Scale> scales = scaleMapper.selectByScaleIds(scaleIds);

//            获取商品中不同规格的价格
                    List<BigDecimal> list = new ArrayList<>();

                    scales.forEach(s -> {
                        Price result = priceMapper.selectOne(new QueryWrapper<Price>().eq("scaleId", s.getScaleId()).eq("commodityId", c.getId()));
                        if (result != null) {
                            list.add(result.getPrice());
                        }
                    });
//            对价格进行排序
                    price = list.stream().sorted().collect(Collectors.toList());


                }

//             创建CommodityPriceVo封装数据
             CommodityPriceVo commodityPriceVo = new CommodityPriceVo();
             commodityPriceVo.setCommodityDesc(c.getCommodityDesc());
             commodityPriceVo.setCommodityImg(c.getCommodityImg());
             commodityPriceVo.setCommodityName(c.getCommodityName());
             commodityPriceVo.setCommodityType(c.getCommodityType());
             commodityPriceVo.setPriceId(c.getPriceId());
             commodityPriceVo.setFlavorId(c.getFlavorId());
             commodityPriceVo.setId(c.getId());
             commodityPriceVo.setPrices(price);
//             将对象添加到集合中
             listResult.add(commodityPriceVo);
         });

//        将数据存进redis缓存中
        redisCache.setCacheList("CommodityPriceVo"+kind,listResult);
//        返回数据结果
        return ResultUtils.success(SUCCESS,listResult,"","返回特定商品类型的所有商品加价格");
    }
}




